package models

import (
	"time"
	"gorm.io/gorm"
	"admin-glm-go/internal/utils"
)

// Admin 管理员模型
type Admin struct {
	ID           uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Username     string    `json:"username" gorm:"type:varchar(50);uniqueIndex:admin_username_unique;not null"`
	Password     string    `json:"-" gorm:"type:varchar(255);not null"`
	Nickname     string    `json:"nickname" gorm:"type:varchar(50)"`
	Avatar       string    `json:"avatar" gorm:"type:varchar(255)"`
	Email        string    `json:"email" gorm:"type:varchar(100);index:idx_email"`
	Phone        string    `json:"phone" gorm:"type:varchar(20);index:idx_phone"`
	Status       int       `json:"status" gorm:"type:tinyint;default:1;comment:0-禁用，1-启用"`
	LastLoginTime *time.Time `json:"lastLoginTime" gorm:"column:last_login_time"`
	LastLoginIP  string    `json:"lastLoginIp" gorm:"column:last_login_ip;type:varchar(50)"`
	CreateTime   time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime   time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy    *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy    *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Roles        []Role    `json:"roles" gorm:"many2many:admin_role;"`
}

// Role 角色模型
type Role struct {
	ID          uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Name        string    `json:"name" gorm:"type:varchar(50);uniqueIndex:role_code_unique;not null"`
	Code        string    `json:"code" gorm:"type:varchar(50);uniqueIndex:role_code_unique;not null"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	Status      int       `json:"status" gorm:"type:tinyint;default:1;comment:0-禁用，1-启用"`
	CreateTime  time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime  time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy   *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy   *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Permissions []Permission `json:"permissions" gorm:"many2many:role_permission;"`
}

// Permission 权限模型
type Permission struct {
	ID          uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Name        string    `json:"name" gorm:"type:varchar(50);not null"`
	Code        string    `json:"code" gorm:"type:varchar(100);uniqueIndex:permission_code_unique;not null"`
	Type        int       `json:"type" gorm:"type:tinyint;comment:权限类型：1-菜单，2-按钮"`
	ParentID    uint64    `json:"parentId" gorm:"column:parent_id;type:bigint;default:0;comment:父权限ID，根权限为0"`
	Path        string    `json:"path" gorm:"type:varchar(100)"`
	Icon        string    `json:"icon" gorm:"type:varchar(50)"`
	Component   string    `json:"component" gorm:"type:varchar(100)"`
	Permission  string    `json:"permission" gorm:"type:varchar(100)"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	Status      int       `json:"status" gorm:"type:tinyint;default:1;comment:0-禁用，1-启用"`
	Sort        int       `json:"sort" gorm:"type:int;default:0"`
	CreateTime  time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime  time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy   *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy   *uint64   `json:"updatedBy" gorm:"column:updated_by"`
}

// Menu 菜单模型
type Menu struct {
	ID          uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	ParentID    uint64    `json:"parentId" gorm:"column:parent_id;type:bigint;default:0;comment:父菜单ID，根菜单为0"`
	Name        string    `json:"name" gorm:"type:varchar(50);not null"`
	Path        string    `json:"path" gorm:"type:varchar(100)"`
	Icon        string    `json:"icon" gorm:"type:varchar(50)"`
	Component   string    `json:"component" gorm:"type:varchar(100)"`
	Permission  string    `json:"permission" gorm:"type:varchar(100)"`
	Type        int       `json:"type" gorm:"type:tinyint;comment:菜单类型：1-目录，2-菜单，3-按钮"`
	Visible     int       `json:"visible" gorm:"column:visible;type:tinyint;default:1;comment:是否可见：0-隐藏，1-显示"`
	Status      int       `json:"status" gorm:"type:tinyint;default:1;comment:状态：0-禁用，1-启用"`
	IsExternal  int       `json:"isExternal" gorm:"column:is_external;type:tinyint;default:0;comment:是否外链：0-否，1-是"`
	ExternalURL string    `json:"externalUrl" gorm:"column:external_url;type:varchar(255)"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	Sort        int       `json:"sort" gorm:"type:int;default:0"`
	CreateTime  time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime  time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy   *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy   *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Children    []Menu    `json:"children" gorm:"-"`
}

// Article 文章模型
type Article struct {
	ID          uint64       `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	AdminID     *uint64      `json:"adminId" gorm:"column:admin_id;type:bigint;index:idx_admin_id"`
	Title       string       `json:"title" gorm:"type:varchar(255);not null"`
	Summary     string       `json:"summary" gorm:"type:varchar(500)"`
	Content     string       `json:"content" gorm:"type:text"`
	CategoryID  *uint64      `json:"categoryId" gorm:"column:category_id;type:bigint;index:idx_category_id"`
	CoverImage  string       `json:"coverImage" gorm:"column:cover_image;type:varchar(255)"`
	Author      string       `json:"author" gorm:"type:varchar(50)"`
	Source      string       `json:"source" gorm:"type:varchar(100)"`
	Tags        string       `json:"tags" gorm:"type:varchar(255);comment:文章标签，逗号分隔"`
	Status      int          `json:"status" gorm:"type:tinyint;default:0;comment:状态：0-草稿，1-已发布"`
	IsTop       int          `json:"isTop" gorm:"column:is_top;type:tinyint;default:0;comment:是否置顶：0-否，1-是"`
	IsRecommend int          `json:"isRecommend" gorm:"column:is_recommend;type:tinyint;default:0;comment:是否推荐：0-否，1-是"`
	Sort        int          `json:"sort" gorm:"type:int;default:0"`
	ViewCount   int          `json:"viewCount" gorm:"column:view_count;type:int;default:0"`
	LikeCount   int          `json:"likeCount" gorm:"column:like_count;type:int;default:0"`
	PublishTime *time.Time   `json:"publishTime" gorm:"column:publish_time;index:idx_publish_time"`
	CreateTime  time.Time    `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime  time.Time    `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy   *uint64      `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy   *uint64      `json:"updatedBy" gorm:"column:updated_by"`
	Category    Category     `json:"category" gorm:"foreignKey:CategoryID"`
	Admin       Admin        `json:"admin" gorm:"foreignKey:AdminID"`
}

// Category 分类模型
type Category struct {
	ID          uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	ParentID    uint64    `json:"parentId" gorm:"column:parent_id;type:bigint;default:0;comment:父分类ID，根分类为0;index:idx_parent_id"`
	Name        string    `json:"name" gorm:"type:varchar(50);not null"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	Icon        string    `json:"icon" gorm:"type:varchar(100)"`
	Sort        int       `json:"sort" gorm:"type:int;default:0"`
	Status      int       `json:"status" gorm:"type:tinyint;default:1;comment:状态：0-禁用，1-启用"`
	CreateTime  time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime  time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy   *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy   *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Articles    []Article `json:"articles" gorm:"foreignKey:CategoryID"`
	Children    []Category `json:"children" gorm:"foreignKey:ParentID"`
}

// TableName 指定Category表名
func (Category) TableName() string {
	return "category"
}

// Member 会员模型
type Member struct {
	ID           uint64     `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Username     string     `json:"username" gorm:"type:varchar(50);uniqueIndex:member_username_unique;not null"`
	Password     string     `json:"-" gorm:"type:varchar(255);not null"`
	Nickname     string     `json:"nickname" gorm:"type:varchar(50)"`
	Avatar       string     `json:"avatar" gorm:"type:varchar(255)"`
	Email        string     `json:"email" gorm:"type:varchar(100);index:idx_email"`
	Phone        string     `json:"phone" gorm:"type:varchar(20);index:idx_phone"`
	Gender       int        `json:"gender" gorm:"type:tinyint;default:0;comment:性别：0-未知，1-男，2-女"`
	Birthday     *time.Time `json:"birthday" gorm:"type:date"`
	LevelID      *uint64    `json:"levelId" gorm:"column:level_id;type:bigint;index:idx_level_id"`
	Points       int        `json:"points" gorm:"type:int;default:0"`
	Balance      float64    `json:"balance" gorm:"type:decimal(10,2);default:0.00"`
	Status       int        `json:"status" gorm:"type:tinyint;default:1;comment:状态：0-禁用，1-启用"`
	LastLoginTime *time.Time `json:"lastLoginTime" gorm:"column:last_login_time"`
	LastLoginIP  string     `json:"lastLoginIp" gorm:"column:last_login_ip;type:varchar(50)"`
	CreateTime   time.Time  `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime   time.Time  `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy    *uint64    `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy    *uint64    `json:"updatedBy" gorm:"column:updated_by"`
	Level        MemberLevel `json:"level" gorm:"foreignKey:LevelID"`
}

// MemberLevel 会员等级模型
type MemberLevel struct {
	ID             uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Name           string    `json:"name" gorm:"type:varchar(50);not null"`
	MinPoints      int       `json:"minPoints" gorm:"column:min_points;type:int;default:0;index:idx_min_points"`
	MaxPoints      int       `json:"maxPoints" gorm:"column:max_points;type:int;default:0;index:idx_max_points"`
	Description    string    `json:"description" gorm:"type:varchar(255)"`
	Discount       int       `json:"discount" gorm:"type:int;default:100;comment:折扣"`
	Benefits       string    `json:"benefits" gorm:"type:json"`
	Sort           int       `json:"sort" gorm:"type:int;default:0;index:idx_sort"`
	CreateTime     time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime     time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy      *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy      *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Members        []Member  `json:"members" gorm:"foreignKey:LevelID"`
	LevelBenefits  []MemberLevelBenefit `json:"levelBenefits" gorm:"foreignKey:LevelID"`
}

// MemberLevelBenefit 会员等级权益模型
type MemberLevelBenefit struct {
	ID          uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	LevelID     uint64    `json:"levelId" gorm:"column:level_id;type:bigint;index:idx_level_id"`
	Name        string    `json:"name" gorm:"type:varchar(50);not null"`
	Description string    `json:"description" gorm:"type:varchar(255)"`
	Type        int       `json:"type" gorm:"type:tinyint;comment:权益类型：1-折扣，2-积分，3-优惠券，4-专属服务"`
	Value       string    `json:"value" gorm:"type:varchar(100)"`
	CreateTime  time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime  time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy   *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy   *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Level       MemberLevel `json:"level" gorm:"foreignKey:LevelID"`
}

// FriendLinks 友情链接模型
type FriendLinks struct {
	ID        uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Name      string    `json:"name" gorm:"type:varchar(50);not null;comment:链接名称"`
	Url       string    `json:"url" gorm:"type:varchar(255);not null;comment:链接地址"`
	Logo      string    `json:"logo" gorm:"type:varchar(255);comment:链接Logo"`
	Description string   `json:"description" gorm:"type:varchar(255);comment:链接描述"`
	Status    int       `json:"status" gorm:"type:tinyint;default:1;comment:状态：0-禁用，1-启用;index:friend_links_status_index"`
	Sort      int       `json:"sort" gorm:"type:int;default:0;index:friend_links_sort_index"`
	CreatedAt *time.Time `json:"createdAt" gorm:"column:created_at"`
	UpdatedAt *time.Time `json:"updatedAt" gorm:"column:updated_at"`
}

// FriendshipLink 友情链接模型
type FriendshipLink struct {
	ID          uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Name        string    `json:"name" gorm:"type:varchar(50);not null;comment:链接名称"`
	Url         string    `json:"url" gorm:"type:varchar(255);not null;comment:链接地址"`
	Logo        string    `json:"logo" gorm:"column:logo;type:varchar(255);comment:链接LOGO"`
	Description string    `json:"description" gorm:"type:varchar(255);comment:链接描述"`
	Sort        int       `json:"sort" gorm:"type:int;default:0"`
	Status      int       `json:"status" gorm:"type:tinyint;default:1;comment:状态：0-禁用，1-启用"`
	CreateTime  time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime  time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy   *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy   *uint64   `json:"updatedBy" gorm:"column:updated_by"`
}

// OperationLog 操作日志模型
type OperationLog struct {
	ID            uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	AdminID       *uint64   `json:"adminId" gorm:"column:admin_id;type:bigint;index:idx_admin_id"`
	AdminName     string    `json:"adminName" gorm:"column:admin_name;type:varchar(50)"`
	Module        string    `json:"module" gorm:"type:varchar(50);comment:操作模块"`
	Action        string    `json:"action" gorm:"type:varchar(50);comment:操作动作"`
	Method        string    `json:"method" gorm:"type:text;comment:请求方法"`
	Url           string    `json:"url" gorm:"type:varchar(255);comment:请求URL"`
	Params        string    `json:"params" gorm:"type:text;comment:请求参数"`
	Result        string    `json:"result" gorm:"type:text;comment:返回结果"`
	IP            string    `json:"ip" gorm:"type:varchar(50);comment:操作IP"`
	UserAgent     string    `json:"userAgent" gorm:"column:user_agent;type:varchar(255);comment:用户代理"`
	Status        int       `json:"status" gorm:"type:tinyint;default:1;comment:状态：0-失败，1-成功"`
	ErrorMessage  string    `json:"errorMessage" gorm:"column:error_message;type:text;comment:错误信息"`
	CreateTime    time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP;index:idx_create_time"`
	CreatedBy     *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy     *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Admin         Admin     `json:"admin" gorm:"foreignKey:AdminID"`
}

// Settings 系统设置模型
type Settings struct {
	ID          uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Key         string    `json:"key" gorm:"type:varchar(50);uniqueIndex:settings_key_unique;not null;comment:设置键"`
	Value       string    `json:"value" gorm:"type:text;comment:设置值"`
	Description string    `json:"description" gorm:"type:varchar(255);comment:设置描述"`
	Type        int       `json:"type" gorm:"type:tinyint;default:1;comment:设置类型：1-字符串，2-数字，3-布尔，4-JSON"`
	CreateTime  time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime  time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy   *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy   *uint64   `json:"updatedBy" gorm:"column:updated_by"`
}

// SystemSettings 系统设置模型
type SystemSettings struct {
	ID          uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Key         string    `json:"key" gorm:"type:varchar(100);uniqueIndex:system_settings_key_index;not null;comment:设置键"`
	Value       string    `json:"value" gorm:"type:text;comment:设置值"`
	Description string    `json:"description" gorm:"type:varchar(255);comment:设置描述"`
	CreatedAt   *time.Time `json:"createdAt" gorm:"column:created_at"`
	UpdatedAt   *time.Time `json:"updatedAt" gorm:"column:updated_at"`
}

// Users 用户模型
type Users struct {
	ID           uint64     `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Name         string     `json:"name" gorm:"type:varchar(255);not null"`
	Email        string     `json:"email" gorm:"type:varchar(255);uniqueIndex:users_email_unique;not null"`
	EmailVerifiedAt *time.Time `json:"emailVerifiedAt" gorm:"column:email_verified_at"`
	Password     string     `json:"-" gorm:"type:varchar(255);not null"`
	RememberToken string    `json:"rememberToken" gorm:"column:remember_token;type:varchar(100)"`
	CreatedAt    *time.Time `json:"createdAt" gorm:"column:created_at"`
	UpdatedAt    *time.Time `json:"updatedAt" gorm:"column:updated_at"`
}

// PasswordResetTokens 密码重置令牌模型
type PasswordResetTokens struct {
	Email     string     `json:"email" gorm:"primaryKey;type:varchar(255);not null"`
	Token     string     `json:"token" gorm:"type:varchar(255);not null"`
	CreatedAt *time.Time `json:"createdAt" gorm:"column:created_at"`
}

// Sessions 会话模型
type Sessions struct {
	ID           string     `json:"id" gorm:"primaryKey;type:varchar(255);not null"`
	UserID       *uint64    `json:"userId" gorm:"column:user_id;type:bigint;index:sessions_user_id_index"`
	IPAddress    string     `json:"ipAddress" gorm:"column:ip_address;type:varchar(45)"`
	UserAgent    string     `json:"userAgent" gorm:"column:user_agent;type:text"`
	Payload      string     `json:"payload" gorm:"type:longtext;not null"`
	LastActivity int        `json:"lastActivity" gorm:"column:last_activity;type:int;index:sessions_last_activity_index"`
}

// Migrations 迁移模型
type Migrations struct {
	ID        uint   `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	Migration string `json:"migration" gorm:"type:varchar(255);not null"`
	Batch     int    `json:"batch" gorm:"type:int;not null"`
}

// AdminRole 管理员角色关联模型
type AdminRole struct {
	ID         uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	AdminID    uint64    `json:"adminId" gorm:"column:admin_id;type:bigint;not null"`
	RoleID     uint64    `json:"roleId" gorm:"column:role_id;type:bigint;not null"`
	CreateTime time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy  *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy  *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Admin      Admin     `json:"admin" gorm:"foreignKey:AdminID"`
	Role       Role      `json:"role" gorm:"foreignKey:RoleID"`
}

// TableName 指定AdminRole表名
func (AdminRole) TableName() string {
	return "admin_roles"
}

// RolePermission 角色权限关联模型
type RolePermission struct {
	ID           uint64    `json:"id" gorm:"primaryKey;column:id;autoIncrement"`
	RoleID       uint64    `json:"roleId" gorm:"column:role_id;type:bigint;not null"`
	PermissionID uint64    `json:"permissionId" gorm:"column:permission_id;type:bigint;not null"`
	CreateTime   time.Time `json:"createTime" gorm:"column:create_time;default:CURRENT_TIMESTAMP"`
	UpdateTime   time.Time `json:"updateTime" gorm:"column:update_time;default:CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP"`
	CreatedBy    *uint64   `json:"createdBy" gorm:"column:created_by"`
	UpdatedBy    *uint64   `json:"updatedBy" gorm:"column:updated_by"`
	Role         Role      `json:"role" gorm:"foreignKey:RoleID"`
	Permission   Permission `json:"permission" gorm:"foreignKey:PermissionID"`
}

// TableName 指定RolePermission表名
func (RolePermission) TableName() string {
	return "role_permissions"
}

// AutoMigrate 自动迁移数据库表结构
func AutoMigrate(db *gorm.DB) error {
	return db.AutoMigrate(
		&Admin{},
		&Role{},
		&Permission{},
		&Menu{},
		&Article{},
		&Category{},
		&Member{},
		&MemberLevel{},
		&MemberLevelBenefit{},
		&FriendLinks{},
		&FriendshipLink{},
		&OperationLog{},
		&Settings{},
		&SystemSettings{},
		&Users{},
		&PasswordResetTokens{},
		&Sessions{},
		&Migrations{},
		&AdminRole{},
		&RolePermission{},
	)
}

// InitBasicData 初始化基础数据
func InitBasicData(db *gorm.DB) error {
	// 检查是否已有管理员数据
	var adminCount int64
	if err := db.Model(&Admin{}).Count(&adminCount).Error; err != nil {
		return err
	}
	
	// 使用事务确保数据一致性
	return db.Transaction(func(tx *gorm.DB) error {
		// 1. 创建或更新默认管理员
		hashedPassword, err := utils.HashPassword("admin")
		if err != nil {
			return err
		}
		
		admin := Admin{
			Username:   "admin",
			Password:   hashedPassword,
			Nickname:   "超级管理员",
			Email:      "admin@example.com",
			Phone:      "13800138000",
			Status:     1,
			CreatedBy:  uint64Ptr(1),
			UpdatedBy:  uint64Ptr(1),
		}
		
		// 如果没有管理员数据，则创建
		if adminCount == 0 {
			if err := tx.Create(&admin).Error; err != nil {
				return err
			}
			
			// 2. 创建角色
			roles := []Role{
				{Name: "超级管理员", Code: "super_admin", Description: "系统超级管理员，拥有所有权限", Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "管理员", Code: "admin", Description: "系统管理员，拥有大部分权限", Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "编辑", Code: "editor", Description: "内容编辑，拥有内容管理权限", Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
			}
			if err := tx.Create(&roles).Error; err != nil {
				return err
			}
			
			// 3. 创建权限
			permissions := []Permission{
				// 系统管理
				{Name: "系统管理", Code: "system", Type: 1, Icon: "el-icon-setting", Path: "/system", Component: "Layout", Permission: "system", Description: "系统管理权限", Sort: 1, ParentID: 0, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "管理员管理", Code: "system.admin", Type: 2, Icon: "el-icon-user", Path: "admin", Component: "system/admin/index", Permission: "system.admin", Description: "管理员管理权限", Sort: 1, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "角色管理", Code: "system.role", Type: 2, Icon: "el-icon-s-custom", Path: "role", Component: "system/role/index", Permission: "system.role", Description: "角色管理权限", Sort: 2, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "权限管理", Code: "system.permission", Type: 2, Icon: "el-icon-lock", Path: "permission", Component: "system/permission/index", Permission: "system.permission", Description: "权限管理权限", Sort: 3, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "菜单管理", Code: "system.menu", Type: 2, Icon: "el-icon-menu", Path: "menu", Component: "system/menu/index", Permission: "system.menu", Description: "菜单管理权限", Sort: 4, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "操作日志", Code: "system.log", Type: 2, Icon: "el-icon-document", Path: "log", Component: "system/log/index", Permission: "system.log", Description: "操作日志权限", Sort: 5, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				
				// 内容管理
				{Name: "内容管理", Code: "content", Type: 1, Icon: "el-icon-document", Path: "/content", Component: "Layout", Permission: "content", Description: "内容管理权限", Sort: 2, ParentID: 0, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "文章管理", Code: "content.article", Type: 2, Icon: "el-icon-tickets", Path: "article", Component: "content/article/index", Permission: "content.article", Description: "文章管理权限", Sort: 1, ParentID: 6, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "分类管理", Code: "content.category", Type: 2, Icon: "el-icon-folder", Path: "category", Component: "content/category/index", Permission: "content.category", Description: "分类管理权限", Sort: 2, ParentID: 6, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				
				// 会员管理
				{Name: "会员管理", Code: "member", Type: 1, Icon: "el-icon-user", Path: "/member", Component: "Layout", Permission: "member", Description: "会员管理权限", Sort: 3, ParentID: 0, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "会员列表", Code: "member.list", Type: 2, Icon: "el-icon-user-solid", Path: "list", Component: "member/list/index", Permission: "member.list", Description: "会员列表权限", Sort: 1, ParentID: 9, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "会员等级", Code: "member.level", Type: 2, Icon: "el-icon-s-flag", Path: "level", Component: "member/level/index", Permission: "member.level", Description: "会员等级权限", Sort: 2, ParentID: 9, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				
				// 系统设置
				{Name: "系统设置", Code: "setting", Type: 1, Icon: "el-icon-tools", Path: "/setting", Component: "Layout", Permission: "setting", Description: "系统设置权限", Sort: 4, ParentID: 0, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "系统配置", Code: "setting.config", Type: 2, Icon: "el-icon-s-tools", Path: "config", Component: "setting/config/index", Permission: "setting.config", Description: "系统配置权限", Sort: 1, ParentID: 12, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "友情链接", Code: "setting.link", Type: 2, Icon: "el-icon-link", Path: "link", Component: "setting/link/index", Permission: "setting.link", Description: "友情链接权限", Sort: 2, ParentID: 12, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
			}
			if err := tx.Create(&permissions).Error; err != nil {
				return err
			}
			
			// 4. 创建菜单
			menus := []Menu{
				// 系统管理
				{Name: "系统管理", Path: "/system", Icon: "el-icon-setting", Component: "Layout", Permission: "system", Type: 1, Sort: 1, ParentID: 0, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "管理员管理", Path: "admin", Icon: "el-icon-user", Component: "system/admin/index", Permission: "system.admin", Type: 2, Sort: 1, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "角色管理", Path: "role", Icon: "el-icon-s-custom", Component: "system/role/index", Permission: "system.role", Type: 2, Sort: 2, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "权限管理", Path: "permission", Icon: "el-icon-lock", Component: "system/permission/index", Permission: "system.permission", Type: 2, Sort: 3, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "菜单管理", Path: "menu", Icon: "el-icon-menu", Component: "system/menu/index", Permission: "system.menu", Type: 2, Sort: 4, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "操作日志", Path: "log", Icon: "el-icon-document", Component: "system/log/index", Permission: "system.log", Type: 2, Sort: 5, ParentID: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				
				// 内容管理
				{Name: "内容管理", Path: "/content", Icon: "el-icon-document", Component: "Layout", Permission: "content", Type: 1, Sort: 2, ParentID: 0, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "文章管理", Path: "article", Icon: "el-icon-tickets", Component: "content/article/index", Permission: "content.article", Type: 2, Sort: 1, ParentID: 7, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "分类管理", Path: "category", Icon: "el-icon-folder", Component: "content/category/index", Permission: "content.category", Type: 2, Sort: 2, ParentID: 7, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				
				// 会员管理
				{Name: "会员管理", Path: "/member", Icon: "el-icon-user", Component: "Layout", Permission: "member", Type: 1, Sort: 3, ParentID: 0, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "会员列表", Path: "list", Icon: "el-icon-user-solid", Component: "member/list/index", Permission: "member.list", Type: 2, Sort: 1, ParentID: 10, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "会员等级", Path: "level", Icon: "el-icon-s-marketing", Component: "member/level/index", Permission: "member.level", Type: 2, Sort: 2, ParentID: 10, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				
				// 系统设置
				{Name: "系统设置", Path: "/setting", Icon: "el-icon-tools", Component: "Layout", Permission: "setting", Type: 1, Sort: 4, ParentID: 0, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "系统配置", Path: "config", Icon: "el-icon-s-tools", Component: "setting/config/index", Permission: "setting.config", Type: 2, Sort: 1, ParentID: 13, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "友情链接", Path: "link", Icon: "el-icon-link", Component: "setting/link/index", Permission: "setting.link", Type: 2, Sort: 2, ParentID: 13, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
			}
			if err := tx.Create(&menus).Error; err != nil {
				return err
			}
			
			// 5. 创建分类
			categories := []Category{
				{Name: "技术分享", Description: "技术相关文章", Sort: 1, Status: 1, ParentID: 0, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "生活随笔", Description: "生活相关文章", Sort: 2, Status: 1, ParentID: 0, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "前端开发", Description: "前端开发相关文章", Sort: 1, Status: 1, ParentID: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "后端开发", Description: "后端开发相关文章", Sort: 2, Status: 1, ParentID: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
			}
			if err := tx.Create(&categories).Error; err != nil {
				return err
			}
			
			// 6. 创建会员等级
			memberLevels := []MemberLevel{
				{Name: "普通会员", MinPoints: 0, MaxPoints: 999, Description: "普通会员等级", Discount: 100, Benefits: "[\"基本功能访问\"]", Sort: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "白银会员", MinPoints: 1000, MaxPoints: 4999, Description: "白银会员等级", Discount: 95, Benefits: "[\"基本功能访问\", \"部分高级功能\"]", Sort: 2, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "黄金会员", MinPoints: 5000, MaxPoints: 9999, Description: "黄金会员等级", Discount: 90, Benefits: "[\"基本功能访问\", \"部分高级功能\", \"专属客服\"]", Sort: 3, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "钻石会员", MinPoints: 10000, MaxPoints: 49999, Description: "钻石会员等级", Discount: 85, Benefits: "[\"基本功能访问\", \"全部高级功能\", \"专属客服\", \"优先体验\"]", Sort: 4, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "超级会员", MinPoints: 50000, MaxPoints: 999999, Description: "超级会员等级", Discount: 80, Benefits: "[\"基本功能访问\", \"全部高级功能\", \"专属客服\", \"优先体验\", \"定制服务\"]", Sort: 5, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
			}
			if err := tx.Create(&memberLevels).Error; err != nil {
				return err
			}
			
			// 7. 创建会员等级权益
			memberLevelBenefits := []MemberLevelBenefit{
				{LevelID: memberLevels[0].ID, Name: "基础权益", Description: "可以浏览基础内容", Type: 1, Value: "基础内容浏览", CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{LevelID: memberLevels[1].ID, Name: "白银权益", Description: "可以浏览基础内容和部分高级内容", Type: 1, Value: "基础内容+部分高级内容", CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{LevelID: memberLevels[2].ID, Name: "黄金权益", Description: "可以浏览基础内容和高级内容", Type: 1, Value: "基础内容+高级内容", CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{LevelID: memberLevels[3].ID, Name: "铂金权益", Description: "可以浏览全部内容和专属客服", Type: 1, Value: "全部内容+专属客服", CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{LevelID: memberLevels[4].ID, Name: "钻石权益", Description: "可以浏览全部内容、专属客服和线下活动", Type: 1, Value: "全部内容+专属客服+线下活动", CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
			}
			if err := tx.Create(&memberLevelBenefits).Error; err != nil {
				return err
			}
			
			// 8. 创建友情链接
			friendshipLinks := []FriendshipLink{
				{Name: "Laravel官网", Url: "https://laravel.com", Logo: "/uploads/link/20231201/1.jpg", Description: "Laravel PHP框架官网", Sort: 1, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "Vue官网", Url: "https://vuejs.org", Logo: "/uploads/link/20231201/2.jpg", Description: "Vue.js框架官网", Sort: 2, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Name: "GitHub", Url: "https://github.com", Logo: "/uploads/link/20231201/3.jpg", Description: "全球最大的代码托管平台", Sort: 3, Status: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
			}
			if err := tx.Create(&friendshipLinks).Error; err != nil {
				return err
			}
			
			// 9. 创建系统设置
			settings := []Settings{
				{Key: "site_name", Value: "Admin GLM PHP", Description: "网站名称", Type: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Key: "site_description", Value: "基于Laravel和Vue的后台管理系统", Description: "网站描述", Type: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Key: "site_keywords", Value: "Laravel,Vue,Admin,GLM,PHP", Description: "网站关键词", Type: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Key: "site_logo", Value: "/uploads/settings/20231201/1.jpg", Description: "网站LOGO", Type: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Key: "site_icp", Value: "京ICP备12345678号", Description: "网站备案号", Type: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
				{Key: "site_copyright", Value: "Copyright © 2023 Admin GLM PHP", Description: "网站版权信息", Type: 1, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)},
			}
			if err := tx.Create(&settings).Error; err != nil {
				return err
			}
			
			// 10. 创建系统设置
			systemSettings := []SystemSettings{
				{Key: "site_name", Value: "GLM管理系统", Description: "网站名称"},
				{Key: "site_description", Value: "基于Laravel和Vue的后台管理系统", Description: "网站描述"},
				{Key: "site_keywords", Value: "Laravel,Vue,管理系统,后台", Description: "网站关键词"},
				{Key: "site_logo", Value: "/uploads/logo.png", Description: "网站Logo"},
				{Key: "site_favicon", Value: "/uploads/favicon.ico", Description: "网站图标"},
				{Key: "site_copyright", Value: "© 2024 GLM管理系统. All rights reserved.", Description: "网站版权信息"},
				{Key: "site_icp", Value: "", Description: "网站备案号"},
				{Key: "upload_max_size", Value: "10", Description: "上传文件最大大小(MB)"},
				{Key: "upload_allowed_types", Value: "jpg,jpeg,png,gif,pdf,doc,docx,xls,xlsx,ppt,pptx,txt,zip,rar", Description: "允许上传的文件类型"},
				{Key: "mail_driver", Value: "smtp", Description: "邮件驱动"},
				{Key: "mail_host", Value: "smtp.example.com", Description: "邮件服务器地址"},
				{Key: "mail_port", Value: "587", Description: "邮件服务器端口"},
				{Key: "mail_username", Value: "noreply@example.com", Description: "邮件用户名"},
				{Key: "mail_password", Value: "", Description: "邮件密码"},
				{Key: "mail_encryption", Value: "tls", Description: "邮件加密方式"},
				{Key: "mail_from_address", Value: "noreply@example.com", Description: "发件人地址"},
				{Key: "mail_from_name", Value: "GLM管理系统", Description: "发件人名称"},
			}
			if err := tx.Create(&systemSettings).Error; err != nil {
				return err
			}
			
			// 11. 关联管理员和角色
			adminRoles := []AdminRole{
				{AdminID: admin.ID, RoleID: roles[0].ID, CreatedBy: uint64Ptr(1), UpdatedBy: uint64Ptr(1)}, // 超级管理员角色
			}
			if err := tx.Create(&adminRoles).Error; err != nil {
				return err
			}
			
			// 12. 关联角色和权限
			var rolePermissions []RolePermission
			// 超级管理员拥有所有权限
			for _, permission := range permissions {
				rolePermissions = append(rolePermissions, RolePermission{
					RoleID:       roles[0].ID,
					PermissionID: permission.ID,
					CreatedBy:    uint64Ptr(1),
					UpdatedBy:    uint64Ptr(1),
				})
			}
			// 管理员拥有部分权限
			for _, permission := range permissions {
				if permission.Code == "system.log" || permission.Code == "setting.config" || permission.Code == "setting.link" {
					continue
				}
				rolePermissions = append(rolePermissions, RolePermission{
					RoleID:       roles[1].ID,
					PermissionID: permission.ID,
					CreatedBy:    uint64Ptr(1),
					UpdatedBy:    uint64Ptr(1),
				})
			}
			// 编辑拥有内容管理权限
			for _, permission := range permissions {
				if permission.Code == "content" || permission.Code == "content.article" || permission.Code == "content.category" {
					rolePermissions = append(rolePermissions, RolePermission{
						RoleID:       roles[2].ID,
						PermissionID: permission.ID,
						CreatedBy:    uint64Ptr(1),
						UpdatedBy:    uint64Ptr(1),
					})
				}
			}
			if err := tx.Create(&rolePermissions).Error; err != nil {
				return err
			}
		} else {
			// 如果已有管理员数据，则更新admin用户的密码
			if err := tx.Model(&Admin{}).Where("username = ?", "admin").Updates(map[string]interface{}{
				"password": hashedPassword,
			}).Error; err != nil {
				return err
			}
			// 获取更新后的admin用户信息
			if err := tx.Where("username = ?", "admin").First(&admin).Error; err != nil {
				return err
			}
		}
		
		return nil
	})
}

// uint64Ptr 返回uint64指针的辅助函数
func uint64Ptr(n uint64) *uint64 {
	return &n
}